// composables/useBreadcrumb.js
import { ref, computed, watch } from 'vue'
import {useI18n} from 'vue-i18n'
export const useBreadcrumb = () => {
  const route = useRoute()
  const router = useRouter()
  const breadcrumbs = ref([])
  const showBreadcrumb = computed(() => {
    // 在首页不显示面包屑，包括带有语言前缀的首页
    // 检查是否为根路径'/'或仅包含语言前缀的路径如'/en'、'/zh'、'/jp'
    const pathArray = route.path.split('/')
    return !(route.path === '/' || (pathArray.length === 2 && ['en', 'zh', 'jp'].includes(pathArray[1])))
  })
  const { t } = useI18n()
  // 路由映射表，用于定义路由对应的面包屑名称
  const routeNameMap = {
    'index': t('home'),
    'android': 'Android应用',
    'apps': t('apps'),
    'games': t('games'),
    'HowTo': t('howto')
  }

  // 根据当前路由生成面包屑
  const generateBreadcrumbs = () => {
    const pathArray = route.path.split('/')
    pathArray.shift() // 移除第一个空元素
    
    let currentPath = ''
    let languagePrefix = ''
    
    // 检查是否有语言参数
    if (route.params.hasOwnProperty('language')) {
      languagePrefix = `/${route.params.language}`
    }
    
    const crumbs = [{
      name: t('home'),
      path: languagePrefix || '/'
    }]

    // 处理语言前缀
    let startIndex = 0
    if (pathArray[0] && ['en', 'zh','jp'].includes(pathArray[0])) {
      currentPath = `/${pathArray[0]}`
      startIndex = 1
      // 确保languagePrefix已设置
      if (!languagePrefix) {
        languagePrefix = currentPath
      }
    }

    // 构建面包屑数组
    for (let i = startIndex; i < pathArray.length; i++) {
      const segment = pathArray[i]
      if (!segment) continue
      
      currentPath += `/${segment}`
      
      // 处理动态路由参数
      if (segment.includes('[') && segment.includes(']')) {
        // 跳过动态路由段，它会在下一个循环中处理
        continue
      }
      
      // 处理带参数的路由（如 [app-slug]）
      if (route.params && Object.keys(route.params).length > 0) {
        const paramKey = Object.keys(route.params).find(key => {
          const paramPattern = `[${key}]`
          const paramPatternWithDash = `[${key.split('-').join('-')}]`
          return segment.includes(paramPattern) || segment.includes(paramPatternWithDash)
        })
        
        if (paramKey && route.params[paramKey]) {
          crumbs.push({
            name: route.params[paramKey],
            path: currentPath
          })
          continue
        }
      }
      
      // 常规路由
      const name = routeNameMap[segment] || segment.charAt(0).toUpperCase() + segment.slice(1)
      crumbs.push({
        name,
        path: currentPath
      })
    }
    
    breadcrumbs.value = crumbs
  }

  // 监听路由变化
  watch(() => route.fullPath, generateBreadcrumbs, { immediate: true })

  return {
    breadcrumbs,
    showBreadcrumb
  }
}